package com.baselib.libnetwork.net.callback;

import com.alibaba.fastjson.JSONObject;
import com.baselib.libnetwork.net.base.Callback;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author lixuce
 * @version v1.0
 * @description
 * @since 2017/10/29
 */

public abstract class JsonCallback<T> implements Callback<T> {

    @Override
    public T convertResponse(Response response) throws Exception {
        ResponseBody body = response.body();
        String json = body.string();
        T t = beforeParseJson(json);
        if (t != null) {
            response.close();
            return afterParseJson(t, json);
        } else {
            Type genType = getClass().getGenericSuperclass();
            Type type = ((ParameterizedType) genType).getActualTypeArguments()[0];

            Object o = JSONObject.parseObject(json, type);

//            Object o = Convert.fromJson(json, type);
            return afterParseJson((T) o, json);
        }
    }


    public T beforeParseJson(String json) {
        return null;
    }

    public T afterParseJson(T t, String json) {
        return t;
    }

    @Override
    public void onProgress(float progress) {

    }

    @Override
    public void onDownloadSuccess(T t) {

    }
}